package org.demo.mine.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ListHashMap <T,V extends IKeyible<T>> extends ArrayList<V> {

	private static final long serialVersionUID = 1L;

	private Map<T, Integer> maps;

	public Map<T, Integer> getMaps() {
		return maps;
	}

	public void setMaps(Map<T, Integer> maps) {
		this.maps = maps;
	}

	public void RecreateMaps() {
		maps.clear();
		for (int i = 0; i < super.size(); i++) {
			T key = super.get(i).Key();
			maps.put(key, i);
		}
	}

	public ListHashMap() {
		super();
		maps = new HashMap<T, Integer>();
	}

	public boolean containsKey(String key) {
		return maps.containsKey(key);
	}

	@Override
	public V set(int index, V element) {
		T key = element.Key();
		if (maps.containsKey(key) == false) {
			return null;
		}
		int int1 = maps.get(key);
		V e = null;
		if (int1 == index) {
			e = super.set(index, element);
		}
		return e;
	}

	@Override
	public boolean add(V e) {
		T key = e.Key();
		if (maps.containsKey(key)) {
			int index1 = maps.get(key);
			super.set(index1, e);
			return true;
		}
		boolean mark1 = super.add(e);
		if (mark1) {
			maps.put(key, super.indexOf(e));
		}
		return mark1;
	}

	@Override
	public void add(int index, V element) {
		T key = element.Key();
		if (maps.containsKey(key)) {
			int index1 = maps.get(key);
			super.remove(index1);
			maps.remove(key);
		}
		super.add(index, element);
		RecreateMaps();
	}

	@Override
	public V remove(int index) {
		V e = super.remove(index);
		RecreateMaps();
		return e;
	}

	@Override
	public boolean remove(Object o) {
		boolean mark1 = super.remove(o);
		RecreateMaps();
		return mark1;
	}

	public boolean remove(String key) {
		if (maps.containsKey(key)) {
			int index1 = maps.get(key);
			super.remove(index1);
			RecreateMaps();
			return true;
		}
		return false;
	}

	@Override
	public void clear() {
		super.clear();
		maps.clear();
	}

	@Override
	public boolean addAll(Collection<? extends V> c) {
		for (V t1 : c) {
			this.add(t1);
		}
		return true;
	}

	@Override
	public boolean addAll(int index, Collection<? extends V> c) {
		return this.addAll(c);
	}

	@Override
	protected void removeRange(int fromIndex, int toIndex) {
		super.removeRange(fromIndex, toIndex);
		RecreateMaps();
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		boolean mark1 = super.removeAll(c);
		RecreateMaps();
		return mark1;
	}

	public V getData(T key) {
		if (maps.containsKey(key) == false) {
			return null;
		}
		return super.get(maps.get(key));
	}

	@Override
	public String toString() {
		String str1 = "";
		for (int i = 0; i < size(); i++) {
			str1 += super.get(i).toString() + "\n";
		}
		return str1;
	}
}
